import java.util.ArrayList;

public class MergeKLists {
    // newcoder 合并k个已排序的链表
    // https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        // write code here
        if (lists.size() == 0) return null;
        return merge(lists, 0, lists.size() - 1);
    }

    public ListNode merge(ArrayList<ListNode> lists, int left, int right) {
        if (left >= right) {
            return lists.get(left);
        }
        int mid = left + (right - left) / 2;
        ListNode leftList = merge(lists, left, mid);
        ListNode rightList = merge(lists, mid + 1, right);
        ListNode pHead = new ListNode(-1);
        ListNode cur1 = leftList, cur2 = rightList, cur3 = pHead;
        while (cur1 != null && cur2 != null) {
            if (cur1.val < cur2.val) {
                cur3.next = cur1;
                cur1 = cur1.next;
            }else {
                cur3.next = cur2;
                cur2 = cur2.next;
            }
            cur3 = cur3.next;
        }
        if (cur1 != null) {
            cur3.next = cur1;
        }
        if (cur2 != null) {
            cur3.next = cur2;
        }
        return pHead.next;
    }
}
